﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ScreenCapture
{
    public partial class Setting : Form
    {
        public Setting()
        {
            InitializeComponent();
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.StartPosition = FormStartPosition.CenterScreen;

            m_keyHook = new KeyHook();
            m_keyHook.KeyHookEvent += new KeyHook.KeyHookHanlder(m_keyHook_KeyHookEvent);
            m_dtLastDownPrt = DateTime.Now;
            this.textBox1.ReadOnly = true;
        }

        private const int HOTKEY_N_ID = 1000;
        private const uint MOD_ALT = 0x1;
        private const uint MOD_CONTROL = 0x2;
        private const uint MOD_SHIFT = 0x4;

        //  private FrmCapture m_frmCapture;
        //保存当前设置的临时变量
        private uint m_uCtrlKey_n;
        private uint m_uAuxKey_n;

        private bool m_bAutoRun;
        private bool m_bCaptureCur;

        private KeyHook m_keyHook;
        private DateTime m_dtLastDownPrt;

        private void Setting_Load(object sender, EventArgs e)
        {
            //   m_keyHook.SetHook();
            if (!this.LoadSetting())
            {  //加载用户设置 如果失败使用默认设置
                if (Win32.RegisterHotKey(this.Handle, HOTKEY_N_ID, MOD_SHIFT | MOD_ALT, (int)Keys.A))
                {
                    ck_alt.Checked = ck_shift.Checked = true;
                    textBox1.Text = "A";
                }

                MessageBox.Show("Load setting fialed!");
                return;
            }
        }


        //从文件加载用户的设置
        private bool LoadSetting()
        {
            //【注意】用绝对路径 如果开机启动的话还没有完全进入系统程序就启动 使用相对路径可能无法找到文件
            if (!File.Exists(Application.StartupPath + "\\CaptureSetting.ini"))      //从文件中获取设置
                return false;
            byte[] byTemp = File.ReadAllBytes(Application.StartupPath + "\\CaptureSetting.ini");
            if (byTemp.Length != 10)
                return false;
            m_uCtrlKey_n = BitConverter.ToUInt32(byTemp, 0);
            m_uAuxKey_n = BitConverter.ToUInt32(byTemp, 4);

            //if (!Win32.RegisterHotKey(this.Handle, HOTKEY_N_ID, m_uCtrlKey_n, m_uAuxKey_n))
            //    return false;
            textBox1.Text = ((Keys)m_uAuxKey_n).ToString();
            ck_ctrl.Checked = (m_uCtrlKey_n & MOD_CONTROL) != 0;
            ck_alt.Checked = (m_uCtrlKey_n & MOD_ALT) != 0;
            ck_shift.Checked = (m_uCtrlKey_n & MOD_SHIFT) != 0;
            ck_autorun.Checked = m_bAutoRun = Convert.ToBoolean(byTemp[8]);
            ck_capturecursor.Checked = m_bCaptureCur = Convert.ToBoolean(byTemp[9]);
            return true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!ck_ctrl.Checked && !ck_alt.Checked && !ck_shift.Checked)
            {
                MessageBox.Show("Maybe you should select a control key!");
                return;     //至少选择一个控制键(alt ctrl shift)
            }
            if (textBox1.Text == "")
            {
                MessageBox.Show("Maybe you should select a auxiliary key!");
                return;     //必须确定一个辅助键(非alt ctrl shift)
            }
            if (ck_autorun.Checked)
            {
                if (DialogResult.No == MessageBox.Show(
                    "\"AutoRun\" will start after the computer start up!\r\n" +
                    "Please keep the path exsit.\r\nContinue?", "question", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    return; //如果选择了开机自起 那么提示保持当前路径的存在
                }
            }
            //如果满足要求开始设置
            m_uCtrlKey_n = 0
                | (ck_ctrl.Checked ? MOD_CONTROL : 0)
                | (ck_alt.Checked ? MOD_ALT : 0)
                | (ck_shift.Checked ? MOD_SHIFT : 0);
            m_uAuxKey_n = Convert.ToUInt32((Keys)Enum.Parse(typeof(Keys), textBox1.Text));


            m_bAutoRun = ck_autorun.Checked;
            m_bCaptureCur = ck_capturecursor.Checked;

            if (!Win32.UnregisterHotKey(this.Handle, HOTKEY_N_ID))                  //卸载原来的热键
                MessageBox.Show("[Normal]The orginal hotkey uninstallation failed!");
            if (!Win32.RegisterHotKey(this.Handle, HOTKEY_N_ID, m_uCtrlKey_n, m_uAuxKey_n))   //登记新的热键
                MessageBox.Show("[Normal]The new hotkey failed to install!");


            //将设置存入文件
            FileStream fs = new FileStream("CaptureSetting.ini", FileMode.Create);
            fs.Write(BitConverter.GetBytes(m_uCtrlKey_n), 0, 4);      //保存控制键
            fs.Write(BitConverter.GetBytes(m_uAuxKey_n), 0, 4);       //保存辅助键

            fs.WriteByte((byte)(m_bAutoRun ? 1 : 0));               //保存是否自起
            fs.WriteByte((byte)(m_bCaptureCur ? 1 : 0));            //保存是否捕获鼠标
            fs.Close();
            try
            {
                RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\", true);
                if (ck_autorun.Checked)
                {
                    if (regKey == null)
                        regKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\");
                    regKey.SetValue("ScreenCapture", Application.ExecutablePath);
                }
                else
                {
                    if (regKey != null)
                    {
                        if (regKey.GetValue("ScreenCapture") != null)
                            regKey.DeleteValue("ScreenCapture");
                    }
                }
                regKey.Close();
            }
            catch (Exception ex)
            {

                //  MessageBox.Show();
            }
            //根据情况是否写入注册表

            MessageBox.Show("Setting Sucess!");
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if ("None" != e.Modifiers.ToString())
            { //禁止输入控制键(非alt ctrl shift...)
                MessageBox.Show("Can not input control keys!");
                return;
            }
            (sender as TextBox).Text = e.KeyCode.ToString();   //显示点下的按键
        }

        private void m_keyHook_KeyHookEvent(object sender, KeyHookEventArgs e)
        {
            if (e.KeyCode == (int)Keys.PrintScreen && ck_capturecursor.Checked)
            {
                if (DateTime.Now.Subtract(m_dtLastDownPrt).TotalMilliseconds > 500)
                    ScreenCapture.DrawCurToScreen();       //如果按下不松开会一直触发
                m_dtLastDownPrt = DateTime.Now;
                //下面是尝试了些在桌面绘制了鼠标之后然后将画上去的鼠标刷掉 结果貌似失败了  算了
                //Console.WriteLine(rect.ToString());
                //Win32.LPRECT lpRect = new Win32.LPRECT() {
                //    Left = rect.Left, Top = rect.Top,
                //    Right = rect.Right, Bottom = rect.Bottom
                //};
                //IntPtr desk = Win32.GetDesktopWindow();
                //IntPtr deskDC = Win32.GetDCEx(desk, IntPtr.Zero, 0x403);
                //Graphics g = Graphics.FromHdc(deskDC);
                //g.FillRectangle(new SolidBrush(Color.FromArgb(128, Color.Red)), new Rectangle(100, 100, 400, 400)); 
                //Console.WriteLine(Win32.RedrawWindow(IntPtr.Zero, ref lpRect, IntPtr.Zero, 0x85));
                //Console.WriteLine((Win32.RDW_INTERNALPAINT | Win32.RDW_INVALIDATE | Win32.RDW_NOERASE).ToString("X"));
                //Console.WriteLine(Win32.InvalidateRect(Win32.GetDesktopWindow(), ref lpRect, false));
                //Console.WriteLine(lpRect.Left + " " + lpRect.Top + " " + lpRect.Right + " " + lpRect.Bottom);
            }
        }
    }
}
